/*
 *
 *  *    Copyright 2020-2021 Luter.me
 *  *
 *  *    Licensed under the Apache License, Version 2.0 (the "License");
 *  *    you may not use this file except in compliance with the License.
 *  *    You may obtain a copy of the License at
 *  *
 *  *      http://www.apache.org/licenses/LICENSE-2.0
 *  *
 *  *    Unless required by applicable law or agreed to in writing, software
 *  *    distributed under the License is distributed on an "AS IS" BASIS,
 *  *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  *    See the License for the specific language governing permissions and
 *  *    limitations under the License.
 *
 */

package com.luter.heimdall.plugins.aspectj;

import com.luter.heimdall.core.annotation.RequiresUser;
import com.luter.heimdall.core.exception.HeimdallUnauthorizedException;
import com.luter.heimdall.core.manager.AuthenticationManager;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;

import java.lang.reflect.Method;

import static com.luter.heimdall.core.authorization.handler.HeimdallMethodAuthorizationHandler.handleRequiresUser;

/**
 * 认证注解处理器
 * <p>
 * 单独处理 @RequiresUser注解
 *
 * @author luter
 */
@Aspect
public class HeimdallAuthenticationAspectHandler {

    /**
     * 切入点
     */
    private static final String POINT_CUP_EXPRESSION =
            "@within(com.luter.heimdall.core.annotation.RequiresUser)||@annotation(com.luter.heimdall.core.annotation.RequiresUser)";

    /**
     * The Authentication manager.
     */
    private final AuthenticationManager authenticationManager;

    /**
     * Instantiates a new Heimdall authentication aspect handler.
     *
     * @param authenticationManager the authentication manager
     */
    public HeimdallAuthenticationAspectHandler(AuthenticationManager authenticationManager) {
        this.authenticationManager = authenticationManager;
    }

    /**
     * 切入点
     */
    @Pointcut(POINT_CUP_EXPRESSION)
    public void pointCut() {
    }

    /**
     * 执行前校验
     *
     * @param joinPoint the join point
     * @throws HeimdallUnauthorizedException the heimdall unauthorized exception
     */
    @Before("pointCut()")
    public void onBefore(JoinPoint joinPoint) throws HeimdallUnauthorizedException {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        final Method method = signature.getMethod();
        if (null == authenticationManager || null == method) {
            return;
        }
        if (method.isAnnotationPresent(RequiresUser.class)
                || method.getDeclaringClass().isAnnotationPresent(RequiresUser.class)) {
            handleRequiresUser(authenticationManager, method);
        }
    }
}
